package com.company.design.create.prototype;

import java.io.*;

/**
 * @author yingfing
 * @create 2020--09--26 16:06
 * @describe 原型类 - 深复制
 * 深复制 : 将一个对象复制后,不论是基本数据类型还有引用类型,都是重新创建的.简单来说 , 就是深复制进行了完全彻底的赋值,而浅复制不彻底
 */
public class Prototype1 implements Cloneable, Serializable {
    private static final long serialVersionUID = 1L;
    private String str;
    private SerializableObject obj;

    /*
    浅复制
     */
    @Override
    protected Object clone() throws CloneNotSupportedException {
        return (Prototype1) super.clone();
    }

    /*深复制*/
    public Object deepClone() throws IOException, ClassNotFoundException {
        // 写入当前对象的二进制流
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(bos);
        oos.writeObject(this);

        // 读出二进制流产生的新对象
        ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
        ObjectInputStream ois = new ObjectInputStream(bis);

        return ois.readObject();
    }
}

class SerializableObject implements Serializable {
    private static final long serialVersionUID = 1L;
}